"""获取有道翻译"""

# -*- coding: utf-8 -*-
# @Author: yqbao
# @GiteeURL: https://gitee.com/yqbao
# @Date: 2019/8/24 17:57
# @Version: v.0.0

from urllib import request, parse
import requests
import json
import hashlib
import time
import random


class YouDaoTranslator:
    def __init__(self):
        self.url = 'http://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule'
        self.headers = {
            'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
            'Cookie': 'OUTFOX_SEARCH_USER_ID=1465596257@10.169.0.84; OUTFOX_SEARCH_USER_ID_NCOO=1130122099.089292; _ntes_nnid=066e08dd80856229b7f88abe8f0d9920,1566639294124; UM_distinctid=16cc361c145758-03e838a648b71a-6353160-100200-16cc361c146897; JSESSIONID=aaaQEX81GaPnkfC_5IdZw; SESSION_FROM_COOKIE=unknown; DICT_UGC=be3af0da19b5c5e6aa4e17bd8d90b28a|; JSESSIONID=abciZGxghhlRK-zlPWdZw; ___rl__test__cookies=1566653144446',
            'Host': 'fanyi.youdao.com',
            'Origin': 'http://fanyi.youdao.com',
            'Referer': 'http://fanyi.youdao.com/',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36',
            'X-Requested-With': 'XMLHttpRequest',
        }
        self.data = {
            'i': '',  # 带翻译的内容
            'from': 'AUTO',
            'to': 'AUTO',
            'smartresult': 'dict',
            'client': 'fanyideskweb',
            'salt': '',  # 待填写的信息
            'sign': '',  # 待填写的签名
            'ts': '',  # 待填写的信息
            'bv': '316dd52438d41a1d675c1d848edf4877',
            'doctype': 'json',
            'version': '2.1',
            'keyfrom': 'fanyi.web',
            'action': 'FY_BY_REALTlME',
        }

    def toke(self, keyword):
        """绘制要加密的签名信息"""
        self.data['i'] = keyword

        # 生成一个毫秒级时间戳
        self.data['ts'] = str(int(time.time() * 1000))

        # 时间戳末尾加上一个0-9的随机数
        self.data['salt'] = self.data['ts'] + str(random.randint(0, 9))

        # 生成一个待加密字符串
        composed_str = 'fanyideskweb' + keyword + self.data['salt'] + 'n%A-rKaT5fb[Gy?;N5@Tj'

        # MD5加密，得出签名
        self.data['sign'] = hashlib.md5(composed_str.encode('utf-8')).hexdigest()

    def query_urllib(self, keyword):
        """urllib方式爬取数据"""
        self.toke(keyword)
        try:
            data = parse.urlencode(self.data).encode('utf-8')  # 编码data数据
            req = request.Request(url=self.url, data=data, headers=self.headers, method='POST')  # 构造完整请求
            response = request.urlopen(req).read().decode('utf-8')  # 请求URL并，抓取响应内容
            str_json = json.loads(response)  # 将响应内容反序列化为python对象
            return str_json['translateResult'][0][0]['tgt']  # 解析数据
        except KeyError:
            return None

    def query_requests(self, keyword):
        """requests方式爬取数据"""
        self.toke(keyword)
        try:
            req = requests.post(url=self.url, headers=self.headers, data=self.data)  # POST请求
            response = req.content.decode('utf-8')  # 抓取响应信息
            str_json = json.loads(response)  # 将响应内容反序列化为python对象
            return str_json['translateResult'][0][0]['tgt']  # 解析数据
        except KeyError:
            return None


if __name__ == '__main__':
    a = YouDaoTranslator()
    while True:
        keywords = input('请输入翻译内容(按q退出)：')
        if keywords != 'q':
            # print(a.query_urllib(keywords))  #urllib方式
            print(a.query_requests(keywords))  # requests方式
        else:
            print('已退出翻译！')
            break
